package com.geek.javaCource.demo.masterslave.datasource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;

import javax.sql.DataSource;

/**
 * Create by chenhd on 2021/9/21.
 */
@Component
public class DataSourceManager {

    @Autowired
    @Qualifier(value = "master")
    DataSource masterDataSource;

    volatile DataSource currentDataSource;

    public DataSource getCurrentDataSource() {
        if (currentDataSource == null) {
            synchronized (DataSources.class) {
                if (currentDataSource == null) {
                    currentDataSource = masterDataSource;
                }
            }
        }
        return currentDataSource;
    }

    public void setCurrentDataSource(DataSource currentDataSource) {
        this.currentDataSource = currentDataSource;
    }

}
